package cn.xiaoyu.android.activity.function.webview;

import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.webkit.WebView;
import android.widget.EditText;
import android.widget.TextView;

import cn.xiaoyu.android.R;

public class WebViewActivity extends AppCompatActivity implements IJsBridge {

    private WebView mWebView;
    private TextView mTvResult;
    private Handler mHandler;
    private EditText mEditText;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_webview);
        initWidgets(savedInstanceState);
    }

    private void initWidgets(Bundle savedInstanceState) {
        mWebView = findViewById(R.id.web_view);
        mTvResult = findViewById(R.id.tv_result);
        mEditText = findViewById(R.id.edit_text);
        findViewById(R.id.btn_remote_add).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String content = mEditText.getText().toString();
                
                mWebView.loadUrl("javascript:if(window.remote){window.remote('" + content + "');}");
            }
        });
        mHandler = new Handler();

        mWebView.getSettings().setJavaScriptEnabled(true);
        // 添加js接口
        mWebView.addJavascriptInterface(new JsInterface(this), "jsTest");

        mWebView.loadUrl("file:///android_asset/www/index.html");
    }

    @Override
    public void setTextViewValue(final String content) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                mTvResult.setText(content);
            }
        });
    }
}
